package uestc.lj.basic.sort;

import java.util.Arrays;

/**
 * 插入排序
 *
 * @Author:Crazlee
 * @Date:2021/11/20
 */
public class Code04_InsertSort {

    public static void insertSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        for (int i = 1; i < array.length; i++) {
            for (int j = i - 1; j >= 0 && array[j] > array[j+1]; j--) {
                swap(array, j, j+1);
            }
        }
    }

    public static void swap(int[] array, int i, int j) {
        array[i] = array[i] ^ array[j];
        array[j] = array[i] ^ array[j];
        array[i] = array[i] ^ array[j];
    }

    public static void main(String[] args) {
        int[] array = {5, 7, 8, 2, 6, 1, 9, 3, 4};
        System.out.println("插入排序之前数组元素为：");
        Arrays.stream(array).forEach(value -> System.out.print(value + " "));
        insertSort(array);
        System.out.println();
        System.out.println("插入排序之后数组的元素为：");
        Arrays.stream(array).forEach(value -> System.out.print(value + " "));
    }
}
